<script setup>
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {doGet, doPost, doPut} from "../http/httpRequest.js";
import {showMessage} from "../util/utils.js";

//定义router对象
let router = useRouter(); //调对象的方法
let route = useRoute(); //点对象的属性

//定义市场活动对象，初始值是空
let activityQuery = ref({})
//定义市场活动的验证规则
let activityRules = ref({
  ownerId : [
    { required: true, message: '请选择负责人', trigger: ['blur', 'change'] }
  ],
  name : [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 3, max: 128, message: '活动名称长度为3-128个字符', trigger: 'blur' }
  ],
  startTime : [
    { required: true, message: '请选择活动开始时间', trigger: 'blur' },
  ],
  endTime : [
    { required: true, message: '请选择活动结束时间', trigger: 'blur' },
  ],
  cost : [
    { required: true, message: '请输入活动预算', trigger: 'blur' },
    { pattern: /^-?\d+(\.\d{1,2})?$/, message: '活动预算必须是整数或者两位小数', trigger: 'blur'}
  ],
  description : [
    { min: 5, max: 255, message: '活动描述长度为5-255个字符', trigger: 'blur' }
  ]
})

//定义负责人的下拉列表数组对象，初始值是空
let ownerOptions = ref([{}])

//加载负责人的函数
const loadOwner = () => {
  doGet('/api/user/owner', {}).then(resp => {
    if (resp.data.code === 200) {
      ownerOptions.value = resp.data.data;
    }
  })
}

//定义form表单的ref属性对象
let activityFormRef = ref();

//提交市场活动（录入市场活动提交）
const activitySubmit = (formEL) => {
  if (!formEL) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEL.validate((valid) => {
    if (valid) {
      let formData = new FormData();
      for (let field in activityQuery.value) {
        if (activityQuery.value[field]) { //该字段有值，我们才放入formData中
          formData.append(field, activityQuery.value[field]);
        }
      }
      //判断是录入还是编辑
      if (activityQuery.value.id > 0) { //编辑活动
        doPut('/api/activity', formData).then(resp => {
          if (resp.data.code === 200) {
            showMessage('编辑成功', 'success');
            //成功后，跳转到列表页
            router.push("/dashboard/activity");
          } else {
            showMessage('编辑失败，原因：' + resp.data.msg, 'error');
          }
        })
      } else {
        doPost('/api/activity', formData).then(resp => {
          if (resp.data.code === 200) {
            showMessage('录入成功', 'success');
            //成功后，跳转到列表页
            router.push("/dashboard/activity");
          } else {
            showMessage('录入失败，原因：' + resp.data.msg, 'error');
          }
        })
      }
    }
  })
}

//返回函数
const goBack = () => {
  router.back();
}

//页面dom元素渲染后执行函数钩子
onMounted(() => {
  //调用一下加载负责人的函数，让负责人的下拉列表数组初始化好数据
  loadOwner();
  let activityId = route.params.activityId;
  if (activityId) {
    //根据activityId查询该活动信息
    loadActivityInfo(activityId);
  }
})

//根据activityId查询该活动信息
const loadActivityInfo = (activityId) => {
  doGet('/api/activity/' + activityId, {}).then(resp => {
    if (resp.data.code === 200) {
      activityQuery.value = resp.data.data;
    }
  })
}
</script>

<template>
  <el-form ref="activityFormRef" :model="activityQuery" label-width="110px" :rules="activityRules">
    <el-form-item label="负责人" prop="ownerId">
      <el-select v-model="activityQuery.ownerId" placeholder="请选择">
        <el-option
            v-for="item in ownerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="活动名称" prop="name">
      <el-input v-model="activityQuery.name" />
    </el-form-item>

    <el-form-item label="开始时间" prop="startTime">
      <el-date-picker
          v-model="activityQuery.startTime"
          type="datetime"
          placeholder="请选择创建时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width:100%;"/>
    </el-form-item>

    <el-form-item label="结束时间" prop="endTime">
      <el-date-picker
          v-model="activityQuery.endTime"
          type="datetime"
          placeholder="请选择创建时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width:100%;"/>
    </el-form-item>

    <el-form-item label="活动预算" prop="cost">
      <el-input v-model="activityQuery.cost" />
    </el-form-item>

    <el-form-item label="活动描述" prop="description">
      <el-input
          v-model="activityQuery.description"
          :rows="8"
          type="textarea"
          placeholder="请输入活动描述"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="activitySubmit(activityFormRef)">提 交</el-button>
      <el-button @click="goBack">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>